<template>
  <div class="dk-minapp-privacy-setting">
    <div v-if="title" class="header mb-4">
      <h3 class="text-lg font-medium">{{ title }}</h3>
    </div>

    <div v-if="settingList.length === 0" class="empty-state text-center py-8 text-gray-500">
      <el-icon class="text-4xl mb-2"><DocumentAdd /></el-icon>
      <p>暂无隐私协议配置</p>
      <p class="text-sm">点击下方"添加隐私项"按钮开始配置</p>
    </div>

    <div v-else class="privacy-table">
      <el-table :data="settingList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />

        <el-table-column label="隐私类型" width="250">
          <template #default="{ row, $index }">
            <el-select
              v-model="row.privacy_key"
              placeholder="请选择或输入隐私类型"
              filterable
              clearable
              allow-create
              default-first-option
              @change="onPrivacyKeyChange($index)"
            >
              <el-option
                v-for="(label, key) in props.privacyOptions"
                :key="key"
                :label="`${label} (${key})`"
                :value="key"
                :disabled="isOptionDisabled(key, $index)"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="收集用途" min-width="300">
          <template #default="{ row }">
            <el-input
              v-model="row.privacy_text"
              type="textarea"
              :rows="2"
              placeholder="请填写收集该信息的用途，无需添加'为了'或'用于'等字眼"
              maxlength="200"
              show-word-limit
              @input="onPrivacyTextChange"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100" align="center">
          <template #default="{ $index }">
            <el-button type="danger" size="small" @click="onRemoveItem($index)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="footer mt-4">
      <div class="flex justify-between items-center">
        <div class="text-sm text-gray-500">
          <span v-if="settingList.length > 0">共 {{ settingList.length }} 项隐私配置</span>
        </div>
        <div class="space-x-2">
          <el-button type="primary" @click="onAddItem">
            <el-icon class="mr-1"><Plus /></el-icon>
            添加隐私项
          </el-button>
          <el-button v-if="settingList.length > 0" @click="onReset">重置</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({
  name: 'DkMinappPrivacySetting'
})

// Props
const props = defineProps({
  title: {
    type: String,
    default: '隐私协议配置'
  },
  modelValue: {
    type: Array,
    default: () => []
  },
  privacyOptions: {
    type: Object,
    default: () => ({
      UserInfo: '用户信息（微信昵称、头像）',
      Location: '位置信息',
      Address: '地址',
      Invoice: '发票信息',
      RunData: '微信运动数据',
      Record: '麦克风',
      Album: '选中的照片或视频信息',
      Camera: '摄像头',
      PhoneNumber: '手机号码',
      Contact: '通讯录（仅写入）权限',
      DeviceInfo: '设备信息',
      EXIDNumber: '身份证号码',
      EXOrderInfo: '订单信息',
      EXUserPublishContent: '发布内容',
      EXUserFollowAcct: '所关注账号',
      EXUserOpLog: '操作日志',
      AlbumWriteOnly: '相册（仅写入）权限',
      LicensePlate: '车牌号',
      BlueTooth: '蓝牙',
      CalendarWriteOnly: '日历（仅写入）权限',
      Email: '邮箱',
      MessageFile: '选中的文件',
      ChooseLocation: '选择的位置信息',
      Accelerometer: '加速传感器',
      Compass: '磁场传感器',
      DeviceMotion: '方向传感器',
      Gyroscope: '陀螺仪传感器',
      Clipboard: '剪切板'
    })
  }
})

// Emits
const emit = defineEmits(['update:modelValue'])

// 响应式数据
const settingList = ref([])

// 初始化数据
const initData = () => {
  if (props.modelValue && props.modelValue.length > 0) {
    settingList.value = props.modelValue.map((item) => ({
      privacy_key: item.privacy_key || '',
      privacy_text: item.privacy_text || ''
    }))
  } else {
    settingList.value = []
  }
}

// 监听props变化
watch(
  () => props.modelValue,
  () => {
    initData()
  },
  { immediate: true }
)

// 添加隐私项
const onAddItem = () => {
  settingList.value.push({
    privacy_key: '',
    privacy_text: ''
  })
}

// 删除隐私项
const onRemoveItem = (index) => {
  if (settingList.value.length === 1) {
    ElMessageBox.confirm('删除后将没有任何隐私配置，确定要删除吗？', '确认删除', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        settingList.value.splice(index, 1)
        updateModelValue()
      })
      .catch(() => {
        // 用户取消删除
      })
  } else {
    settingList.value.splice(index, 1)
    updateModelValue()
  }
}

// 隐私类型变化
const onPrivacyKeyChange = (index) => {
  // 实时同步v-model
  updateModelValue()
}

// 收集用途变化
const onPrivacyTextChange = () => {
  // 实时同步v-model
  updateModelValue()
}

// 判断选项是否被禁用
const isOptionDisabled = (optionKey, currentIndex) => {
  // 检查是否有其他行已经选择了这个选项
  return settingList.value.some((item, index) => {
    return index !== currentIndex && item.privacy_key === optionKey
  })
}

// 更新modelValue - 实时同步数据到父组件
const updateModelValue = () => {
  // 只传递privacy_key和privacy_text两个字段
  const result = settingList.value.map((item) => ({
    privacy_key: item.privacy_key || '',
    privacy_text: item.privacy_text || ''
  }))

  emit('update:modelValue', result)
}

// 获取完整的有效数据（用于保存和验证）
const getValidData = () => {
  return settingList.value
    .filter((item) => {
      return item.privacy_key && item.privacy_key.trim() && item.privacy_text && item.privacy_text.trim()
    })
    .map((item) => ({
      privacy_key: item.privacy_key.trim(),
      privacy_text: item.privacy_text.trim()
    }))
}

// 重置
const onReset = () => {
  ElMessageBox.confirm('确定要重置所有配置吗？此操作不可恢复。', '确认重置', {
    confirmButtonText: '确定重置',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      settingList.value = []
      updateModelValue()
      ElMessage.success('配置已重置')
    })
    .catch(() => {
      // 用户取消重置
    })
}

// 暴露方法给父组件
defineExpose({
  validate: () => {
    const validData = getValidData()
    return validData.length > 0
  },
  getData: () => {
    return getValidData()
  },
  getAllData: () => {
    return settingList.value
  }
})
</script>

<style scoped>
.dk-minapp-privacy-setting {
  padding: 10px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.empty-state {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background: #fafafa;
}

.privacy-table :deep(.el-table) {
  border-radius: 8px;
}

.privacy-table :deep(.el-table th) {
  background: #f5f7fa;
}

.footer {
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}
</style>
